package lev01_beginnerClass.class02_sort;

import java.util.Arrays;

/**
 * insert Sort
 */
public class L03_insertSort {

    public static void main(String[] args) {
        int[] arr = {3,34,56,6,4,67,3,4,6,677,5,3,532,3};

        System.out.println(Arrays.toString(arr));
        insertSortV2(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void insertSort(int[] arr){
        // give priority ro boundary condition
        if(arr == null || arr.length<=1){
            return;
        }

        int len = arr.length;

        for(int end = 1;end <= len-1;end++){
            int newIndex = end;
            while(newIndex -1 >= 0 && arr[newIndex]<arr[newIndex-1]){
                swap(arr,newIndex,newIndex-1);
                newIndex--;
            }
        }

    }

    public static void insertSortV2(int[] arr){
        //boundary condition
        if(arr == null || arr.length <= 1){
            return;
        }

        int len = arr.length;

        for(int end = 1;end <= len-1;end++){
            for(int pre = end -1;pre>= 0 && arr[pre] >= arr[pre+1];pre-- ){
                swap(arr,pre,pre+1);
            }
        }
    }


    public static void swap(int[] arr,int i,int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

}
